package com.example.utils;

import com.example.model.WxbMemeber;
import com.example.util.WxbMemeberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class ZimeitiRealm extends AuthorizingRealm {

    @Autowired
    private WxbMemeberService wxbMemeberService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //1、获取当前登录的用户信息
        WxbMemeber wxbMemeber = (WxbMemeber) SecurityUtils.getSubject().getPrincipal();

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        String md5Pwd = new SimpleHash("md5",password,ByteSource.Util.bytes(username),56).toHex();
        //根据用户名查询用户对象信息
        WxbMemeber wxbMemeber = wxbMemeberService.findByName(token.getUsername());
        if (wxbMemeber == null) {
            throw new UnknownAccountException("账号不存在");
        }else if ( !wxbMemeber.getPassword().equals(md5Pwd)){
            throw new IncorrectCredentialsException("密码错误");
        }
        // 直接将其封装为 返回的数据类型
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(wxbMemeber,wxbMemeber.getPassword(), ByteSource.Util.bytes(wxbMemeber.getAccount()), getName());
        return authenticationInfo;
    }
}
